import { useEffect, useState } from 'react';
import { Row, Col, Divider, List, Typography } from 'antd';
import { useNavigate, Link } from 'react-router-dom';

import { ACCOUNT, WORK_DETAIL, ROLE_DETAIL } from '@/config/url';
import { getKeyFromUrl } from '@/utils';
import { MERCH_NATURE } from '@/config';
import { getMerchInfo, getWorkInfo, getRoleInfo, getMerchHistory, getWorkHistory, getRoleHistory } from '@/service/api';

import styles from './index.module.scss';

export default props => {
    const initState = () => ({
        merch: {},
        items: [],
        loading: false,
        pageNo: 1,
        pageSize: 12,
        total: 0,

        expanded: false,
    });
    const [state, setState] = useState(initState);
    const id = getKeyFromUrl('id');
    const type = getKeyFromUrl('type');
    const navigate = useNavigate();

    const config = {
        merch: {
            mainImage: 'mainGoodsImages',
            list: [
                {key: 'seriesName', label: '作品', render: (input, o) => {
                    const seriesList = Array.isArray(input.seriesList) ? input.seriesList : [];
                    if (!seriesList.length) return null;
                    
                    return seriesList.map((item) => {
                        if (!item.id || !item.seriesName) return null;
                        return <div key={item.id} className={styles['tag']}><Link to={`${WORK_DETAIL}?id=${item.id}`}>{item.seriesName}</Link></div>
                    }).filter(Boolean);
                }},
                {key: 'charactarName', label: '角色', render: (input, o) => {
                    const charactarList = Array.isArray(input.charactarList) ? input.charactarList : [];
                    if (!charactarList.length) return null;
                    
                    return charactarList.map((item) => {
                        if (!item.id || !item.charactarName) return null;
                        return <div key={item.id} className={styles['tag']}><Link to={`${ROLE_DETAIL}?id=${item.id}`}>{item.charactarName}</Link></div>
                    }).filter(Boolean);
                }},
                {key: 'nature', label: '性质', render: (input, o) => MERCH_NATURE.find(i => i.value === input?.[o.key])?.label},
                {key: 'categoryName', label: '品类'},
                {key: 'author', label: '作者', render: (input, o) => {
                    return (input?.[o.key]||'').split(',').filter(Boolean).map((item, index) => {
                        return <div key={index} className={styles['tag']}>{item}</div>
                    })
                }},
                {key: 'publicationYear', label: '年份'},
                {key: 'madeIn', label: '产国'},
                {key: 'introduce', label: '详情', render: (input, o) => {
                    if(!input?.[o.key]) return null;
                    return (
                        <Typography.Paragraph
                            ellipsis={{
                                rows: 2,
                                expandable: 'collapsible',
                                expanded: state.expanded,
                                onExpand: (_, info) => setState(o => ({...o, expanded: info.expanded})),
                            }}
                            copyable={false}
                        >
                            {input?.[o.key] || ''}
                        </Typography.Paragraph>
                    );
                }},
            ],
        },
        work: {
            mainImage: 'mainSeriesImage',
            list: [
                {key: 'seriesName', label: '作品名称', render: (input, o) => {
                    return <div className={styles['tag']}><Link to={`${WORK_DETAIL}?id=${input['id']}`}>{input?.[o.key] || ''}</Link></div>
                }},
                {key: 'publicationYear', label: '发行年份'},
                {key: 'author', label: '作者', render: (input, o) => {
                    return (input?.[o.key]||'').split(',').filter(Boolean).map((item, index) => {
                        return <div key={index} className={styles['tag']}>{item}</div>
                    })
                }},
                {key: 'contributingAuthor', label: '参与创作', render: (input, o) => {
                    return (input?.[o.key]||'').split(',').filter(Boolean).map((item, index) => {
                        return <div key={index} className={styles['tag']}>{item}</div>
                    })
                }},
                {key: 'searchNames', label: '检索名称', render: (input, o) => {
                    return (input?.[o.key]||[]).filter(Boolean).map((item, index) => {
                        return <div key={index} className={styles['tag']}>{item}</div>
                    })
                }},
            ],
        },
        role: {
            mainImage: 'mainCharactarImage',
            list: [
                {key: 'charactarName', label: '角色名', render: (input, o) => {
                    return <div className={styles['tag']}><Link to={`${ROLE_DETAIL}?id=${input['id']}`}>{input?.[o.key] || ''}</Link></div>
                }},
                {key: 'seriesList', label: '所属作品', render: (input, o) => {
                    const seriesList = Array.isArray(input.seriesList) ? input.seriesList : [];
                    if (!seriesList.length) return null;
                    
                    return seriesList.map((item) => {
                        if (!item.id || !item.seriesName) return null;
                        return <div key={item.id} className={styles['tag']}><Link to={`${WORK_DETAIL}?id=${item.id}`}>{item.seriesName}</Link></div>
                    }).filter(Boolean);
                }},
                {key: 'searchNames', label: '检索名称', render: (input, o) => {
                    return (input?.[o.key]||[]).filter(Boolean).map((item, index) => {
                        return <div key={index} className={styles['tag']}>{item}</div>
                    })
                }},
            ],
        }
    };

    /*
        type: merch, work, role
        merch: getMerchDetail/getMerchHistory
        work: getWorkDetail/getWorkHistory
        role: getRoleDetail/getRoleHistory
    */
    // 获取详情（根据 type 调用对应接口）
    const getInfo = async () => {
        setState(s => ({ ...s, loading: true }));
        try {
            let api = getMerchInfo;
            if (type === 'work') api = getWorkInfo;
            if (type === 'role') api = getRoleInfo;

            const [res, error] = await api({ id });
            setState(s => ({ ...s, merch: res?.data || {} }));
        } finally {
            setState(s => ({ ...s, loading: false }));
        }
    };
    // 获取列表
    const getList = async (options = {}) => {
        const { pageNo, pageSize } = state;
        const queryData = { id, pageNo, pageSize, ...options };

        setState(s => ({ ...s, loading: true }));
        try {
            let api = getMerchHistory;
            if (type === 'work') api = getWorkHistory;
            if (type === 'role') api = getRoleHistory;

            const [res, error] = await api(queryData);
            const { records = [], current, total, size } = res?.data || {};
            setState(s => ({
                ...s,
                items: (current === 1 ? [] : state.items).concat(records),
                pageNo: current,
                pageSize: size,
                total,
            }));
        }catch(e){
            setState(s => ({ ...s, loading: false }));
        }
    };

    // 改变页面
    const onChange = (pageNo, pageSize) => {
        getList({ pageNo, pageSize });
    };

    // 去用户中心
    const toAccount = (item) => {
        navigate(`${ACCOUNT}?uid=${item?.memberId || ''}`)
    };

    // 首次加载
    useEffect(() => {
        if (id && type) {
            setState(o => ({ ...o, id, type }));
            getInfo(); // 获取详情
            getList(); // 获取变更历史
        }
    }, []);

    return (
        <div className={styles['container']}>
            <section className={styles['base-info']}>
                <Row gutter={[24, 24]} align="top">
                    <Col xs={24} sm={6} md={6} lg={6} xl={6} xxl={6}>
                        <div className={styles['image-holder']}>
                            <img src={state.merch?.[config[type].mainImage] || ''} alt={''} />
                        </div>
                    </Col>
                    <Col xs={24} sm={18} md={18} lg={18} xl={18} xxl={18}>
                        <div className={styles['info-list']}>
                            {
                                (config[type]['list'] || []).map((item, index) => {
                                    return (
                                        <div className={styles['info']} key={item.key}>
                                            <div className={styles['label']}>{item.label}：</div>
                                            <div className={styles['value']}>{item?.render?.(state.merch, item) || state.merch?.[item.key] || ''}</div>
                                        </div>
                                    )
                                })
                            }
                        </div>
                    </Col>
                </Row>
            </section>

            <Divider/>
            <section className={styles['history']}>
                <h3>变更历史</h3>
                <List
                    className={styles['list']}
                    dataSource={state.items || []}
                    renderItem={(item) => (
                        <List.Item className={styles['item']} key={item.id}>
                            <div className={styles['col-user']} onClick={toAccount.bind(null, item)}>
                                <img src={item.memberAvatar ? `${item.memberAvatar}?x-oss-process=image/resize,p_20` : '/images/default-avatar.png'} className={styles['avatar']} />
                                <span className={styles['nickname']}>{item.memberNickName}</span>
                            </div>
                            <div className={styles['col-time']}>{item.changeTime}</div>
                        </List.Item>
                    )}
                    loading={state.loading}
                    pagination={{
                        align: 'center',
                        hideOnSinglePage: true,
                        current: state.pageNo,
                        pageSize: state.pageSize,
                        total: state.total,
                        onChange: onChange,
                    }}
                />
            </section>
        </div>
    )
}